<template>
  <div class="tag-box">
    <el-tag
      v-for="(layer, index) in layers"
      :key="index"
      :closable="layer === activeElement ? true : false"
      size="small"
      :type="layer === activeElement ? '' : 'info'"
      @click="
        (e) => {
          activeLayer(e, layer);
        }
      "
      @close="
        (e) => {
          dele(e, layer);
        }
      "
      >{{ layer.title }}</el-tag
    >
  </div>
</template>

<script>
import { getVptd } from "../../utils/compat";
import { cumulativeOffset, checkInView } from "../../utils/offset";

import { defineComponent, getCurrentInstance, computed } from "vue-demi";
export default defineComponent({
  name: "layers",
  setup() {
    const instance = getCurrentInstance();
    const vptd = getVptd(instance);

    const layers = computed(() => {
      return vptd.state.page.tempItems;
    });
    const activeElement = computed(() => {
      return vptd.state.activeElement;
    });
    const activeLayer = (e, item) => {
      vptd.commit("select", {
        uuid: item.uuid,
      });
      let viewport = document.querySelector("#viewport");
      if (viewport) {
        let target = viewport.querySelector(`[data-uuid='${item.uuid}']`);
        if (target && !checkInView(target)) {
          viewport.scrollTop = cumulativeOffset(target).top - 50;
        }
      } else {
        console.error('未找到 "#viewport" 的节点');
      }
    };
    const dele = (e, item) => {
      vptd.commit("delete", item.uuid);
    };
    return {
      layers,
      activeElement,
    };
  },
});
</script>
<style lang="scss">
.tag-box {
  .el-tag {
    margin-bottom: 10px;
    margin-right: 10px;
  }
}
</style>
